package com.authine.cloudpivot.ext.service.ipml;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.controller.FrontEndMachineController;
import com.authine.cloudpivot.engine.api.facade.BizObjectFacade;
import com.authine.cloudpivot.engine.api.facade.UserFacade;
import com.authine.cloudpivot.engine.api.facade.WorkflowInstanceFacade;
import com.authine.cloudpivot.engine.api.model.dto.SimpleMsgDTO;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectModel;
import com.authine.cloudpivot.engine.enums.type.IMMessageChannelType;
import com.authine.cloudpivot.engine.enums.type.IMMessageType;
import com.authine.cloudpivot.engine.service.impl.component.RuntimeMessageComponent;
import com.authine.cloudpivot.engine.service.message.IMessageService;
import com.authine.cloudpivot.foundation.orm.api.dml.JPANativeQuery;
import com.authine.cloudpivot.util.CoordtransformUtils;
import com.authine.cloudpivot.util.DateUtil;
import com.authine.cloudpivot.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SyncErrorDataServiceImpl {

    private static final String USERID = "6b42ebe5236d4ecd84332710e5285fd0";

    private static final String DEPID = "ff8080819431dab7019444d8f9e10f01";

    private static final String WORKFLOW_CODE = "ce_001";

    @Autowired
    JPANativeQuery jpaNativeQuery;

    @Autowired
    private BizObjectFacade bizObjectFacade;

    @PersistenceContext
    private EntityManager entityManager;
    @Autowired
    FrontEndMachineController frontEndMachineController;

    @Autowired
    private WorkflowInstanceFacade workflowInstanceFacade;

    @Autowired
    private UserFacade userFacade;

    @Autowired
    private RedisTemplate redisTemplate;

    @Transactional
    public void syncErrorData() {
        Date now = new Date();
        Date start = DateUtil.addHour(now, -1);
        Date end = DateUtil.addHour(now, 1);
        String sql = String.format("SELECT * FROM `ikhmj_alarmdata` where eventtheme is not null and createdTime BETWEEN '%s' and '%s'",DateUtil.dateToStr(start),DateUtil.dateToStr(end));
        List<Map<String,Object>> list = jpaNativeQuery.getList(sql, null, null);
        if (CollectionUtils.isNotEmpty(list)){
            for (Map<String, Object> map : list){
                String jd =(String) map.get("belong_street");
                String sq =(String) map.get("belong_community");
                String wg =(String) map.get("belong_grid");
                String eventtheme =(String) map.get("eventtheme");
                String oneclass =(String) map.get("oneclass");
                String twoclass =(String) map.get("twoclass");
                String threeclass =(String) map.get("threeclass");
                StringBuffer sb = new StringBuffer();
                sb.append("SELECT id FROM `ikhmj_chuishao_001` where DeptSingle1698920071463= '")
                        .append(jd)
                        .append("' and DeptSingle1698920069239='")
                        .append(sq)
                        .append("' and DeptSingle1698920067265='")
                        .append(wg)
                        .append("' and Dropdown1685712329221='")
                        .append(eventtheme)
                        .append("' and  Dropdown1685712342343='")
                        .append(oneclass)
                        .append("' and ejfl='")
                        .append(twoclass)
                        .append("' and sjfl='")
                        .append(threeclass)
                        .append("' and createdTime BETWEEN '")
                        .append(DateUtil.dateToStr(start))
                        .append("' and '")
                        .append(DateUtil.dateToStr(end)).append("'");
                List<Map<String,Object>> chuishao = jpaNativeQuery.getList(sb.toString(), null, null);
                if (CollectionUtils.isNotEmpty(chuishao)){
                    BizObjectCreatedModel bizObject = bizObjectFacade.getBizObject("AlarmData",(String)map.get("id"));
                    List<Map<String,Object>> zb =(List<Map<String, Object>>) bizObject.get("alarm_cs");
                    List<String> ids = chuishao.stream().map(m -> (String) m.get("id")).collect(Collectors.toList());
                    List<String> zbIds = zb.stream().map(m -> {
                        Map<String,Object> o =(Map<String, Object>) m.get("cs_id");
                        if (MapUtils.isEmpty(o)){
                            return null;
                        }
                        return o.get("id").toString();
                    }).collect(Collectors.toList());
                    for (String id:ids){
                        if (!zbIds.contains(id)){
                            String insertSql = String.format("INSERT INTO `ikhmj_alarm_cs` ( `confirm`, `cs_id`, `id`, `modifiedTime`, `modifier`, `parentId`, `sortKey`, `version` )\n" +
                                    "VALUES\n" +
                                    "\t( NULL, '%s', '%s', '%s', '%s', '%s', 0.00000000, NULL );",id, UUID.fastUUID(),DateUtil.dateToStr(now),bizObject.getCreater().getId(),bizObject.getId());
                            Query nativeQuery = entityManager.createNativeQuery(insertSql);
                            nativeQuery.executeUpdate();
                        }
                    }
                }
            }
        }
    }

    /**
     * 雪亮自动发起流程
     */

    public void processCs(Date startTime,Date endTime)  {
        try {
            Date now = new Date();
            Date start = DateUtil.addHour(now, -16);
            if (startTime != null && endTime !=null){
                start = startTime;
                now = endTime;
            }
            String sql =String.format("SELECT * FROM `ikhmj_alarmdata` where eventtheme is not null and createdTime BETWEEN '%s' and '%s' and belong_street = '2c9a8e6488ebff8b0188f03312ab02e0'",DateUtil.dateToStr(start),DateUtil.dateToStr(now));
//            String sql =String.format("SELECT * FROM `ikhmj_alarmdata` where eventtheme is not null limit 1");
//            String sql =String.format("SELECT * FROM `ikhmj_alarmdata` where eventtheme is not null and createdTime BETWEEN '2025-04-08 17:00:00' and '2025-03-21 09:00:00' and belong_street = '2c9a8e6488ebff8b0188f03312ab02e0'");
            List<Map<String,Object>> list = jpaNativeQuery.getList(sql, null, null);
            if (CollectionUtils.isNotEmpty(list)){
                for (Map<String, Object> map : list){
                    String sxt =(String) map.get("channelCode");
                    String processSql= String.format("select * from ikhmj_chuishao_001 where sxtcode = '%s' and sequenceStatus = 'PROCESSING' and  NVL(eventStatus, '') <> '删除'",sxt);
//                    String processSql= String.format("select * from ikhmj_chuishao_001 where sxtcode = '%s' and sequenceStatus = 'PROCESSING' ",sxt);
                    List list1 = jpaNativeQuery.getList(processSql, null, null);
                    if (CollectionUtils.isEmpty(list1)){
                        BizObjectCreatedModel bizObject = bizObjectFacade.getBizObject("AlarmData",(String)map.get("id"));
                        BizObjectModel alarmBizobojectModel = frontEndMachineController.creeateCsData(bizObject);
                        String deptId = (String) map.get("createdDeptId");
                        String userId = (String) map.get("creater");
                        workflowInstanceFacade.startWorkflowInstance(deptId, userId, null, WORKFLOW_CODE, alarmBizobojectModel, null, null, null, Boolean.TRUE);
                    }
                }
            }
        } catch (Exception e) {
            log.info("雪亮数据发起流程失败");
            throw new RuntimeException(e);
        }
    }


    public void pushTimedOutToDo() {


        String title="超时提醒";
        String cont="您的【%s】已经超时，请及时处理！";

        Date nowTime = new Date(); //先取当前时间
        String querySql = String.format("SELECT\n" +
                "    v.id,\n" +
                "    v.gjblsx,\n" +
                "    v.createdTime,\n" +
                "    bim.instanceName,\n" +
                "    bim.participant,\n" +
                "    bim.instanceId,\n" +
                "    bim.activityCode,\n" +
                "    bim.startTime\n" +
                "FROM\n" +
                "    biz_workitem bim\n" +
                "    LEFT JOIN ikhmj_chuishao_001 v ON bim.instanceId = v.workflowInstanceId\n" +
                "WHERE\n" +
                "    bim.workflowCode = 'ce_001'\n" +
                "    and v.sequenceStatus = 'PROCESSING'\n" +
                "    and v.sxtcode is not null");


        List list =null;
        try {

            list = jpaNativeQuery.getList(querySql, null, null);
        } catch (Exception e) {
            log.info("超时提醒查询SQL:",querySql);
            log.error("查询异常：",e);
        }
        if (org.apache.commons.collections.CollectionUtils.isEmpty(list)){
            log.info("超时提醒无数据需要推送");
            return;
        }
        //创建推送服务
        IMessageService messageService = RuntimeMessageComponent.getMessageService(IMMessageChannelType.DINGTALK.name());
        for (Object res : list) {
            HashMap map = (HashMap) res;
            Integer gjblsx = org.apache.commons.collections.MapUtils.getInteger(map, "gjblsx");
            String time = StringUtil.dateTransition(org.apache.commons.collections.MapUtils.getString(map, "createdTime"),"yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date startTime = null;
            try {
                startTime = simpleDateFormat.parse(time);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            long between = cn.hutool.core.date.DateUtil.between(startTime, nowTime, DateUnit.HOUR);
            if (between>gjblsx){
                String instanceName = org.apache.commons.collections.MapUtils.getString(map, "instanceName");
                String participant = org.apache.commons.collections.MapUtils.getString(map, "participant");
                cont = String.format(cont,instanceName);
                UserModel user = userFacade.get(participant);
                String id = org.apache.commons.collections.MapUtils.getString(map, "id");
                String key = id+"_"+participant;
//                if (redisTemplate.hasKey(key)){
//                    continue;
//                }
                this.senDingTalkMessage(messageService,user,title,cont);
                redisTemplate.opsForValue().set(key,null, gjblsx, TimeUnit.DAYS);
                log.info("【待办超时推送消息】：用户:{}，标题：{}，内容：{}",user.getName() ,title, cont);
            }
        }

    }



    /**
     * 验证当前时间是否需要进行推送
     * @return  true=不推送  false = 提送
     * */
    private  boolean virifyPush(){
        int hour = LocalDateTime.now().getHour();

        List list = jpaNativeQuery.getList("select * from push_hour ", null, null);
        HashMap hashMap = (HashMap) list.get(0);
        Integer start = org.apache.commons.collections.MapUtils.getInteger(hashMap, "start", 0);
        Integer end = org.apache.commons.collections.MapUtils.getInteger(hashMap, "end", 24);


        if (start <= hour && end >= hour ){
            return false;
        }

        log.warn("当前时间段为：{}时，不进行推送",hour);
        return true;
    }


    /**
     * 验证当前时间是否需要进行推送
     * @return  true=推送  false = 不提送
     * */
    private  boolean virifyPush(LocalDateTime localDateTime,LocalDateTime startTime,Integer integer){

        Duration duration = Duration.between(startTime, localDateTime);
        long minutes = duration.toMinutes();

        long pus = minutes % 60;
        //只有pus 值 在 0 和 10 之间可以推送
        if(integer >pus && 0 <= pus && 10 >= pus){
            return true;
        }

        log.debug("当前时间不在推送时间范围不进行推送， 实际相差：{}分钟",pus);
        return false;
    }



    private void senDingTalkMessage(IMessageService messageService, UserModel user , String title, String content){

        if (StringUtils.isEmpty(user.getUserId())){
            log.warn("用户钉钉ID为空，不推送钉钉消息！");
            return;
        }

        SimpleMsgDTO dto = new SimpleMsgDTO();
        try {

            //钉钉userId
            dto.setReceivers(user.getUserId());
            dto.setContent(content);
            dto.setTitle(title);
            dto.setMessageType(IMMessageType.BUSINESS_REMIND);
            dto.setCorpId(user.getCorpId());
            messageService.sendSimpleTextMsg(dto);
        } catch (Exception e) {
            log.info("用户：{}-账号：{}，送消息内容：{}",user.getName(),user.getUsername(), JSONObject.toJSONString(dto));
            log.error("钉钉消息发送失败",e);
        }
    }
}
